package com.order.manager.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

@Component
public class ImageUtil {
    public static String encodeImageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        byte[] imageBytes = bos.toByteArray();
        fis.close();
        bos.close();

        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return base64Image;
    }

    public static byte[] decodeBase64ToImage(String base64Image) {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        return imageBytes;
    }

    public static void main(String[] args) throws IOException {
        String imagePath = "C:\\Users\\24862\\Pictures\\Screenshots\\tiange.png";

        // Encode image to Base64
        String base64Image = encodeImageToBase64(imagePath);
//        System.out.println("Base64 Image: " + base64Image);

        // Decode Base64 to image
        byte[] imageBytes = decodeBase64ToImage(base64Image);
        // Save imageBytes to file or display the image
    }

    /**
     * 按尺寸原比例缩放图片
     * @param source 输入源
     * @param output 输出源
     * @param width 256
     * @param height 256
     * @throws IOException
     */
    public static void imgThumb(String source, String output, int width, int height) throws IOException {
        Thumbnails.of(source).size(width, height).toFile(output);
    }

    /**
     * 按照比例进行缩放
     * @param source 输入源
     * @param output 输出源
     * @param scale  比例
     * @throws IOException
     */
    public static void imgScale(String source, String output, double scale) throws IOException {
        Thumbnails.of(source).scale(scale).toFile(output);
    }


}
